package com.example.multiaccountfetcher.strategy.impl;

import com.example.multiaccountfetcher.model.RequestParams;
import com.example.multiaccountfetcher.strategy.DataFetchStrategy;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 模拟第二个API接口的数据拉取策略
 */
@Component
public class MockApiTwoFetchStrategy implements DataFetchStrategy {
    
    // 存储每个账号的最大拉取次数（不同账号可能有不同限制）
    private static final Map<String, Integer> ACCOUNT_MAX_FETCH = new HashMap<>();
    static {
        // 示例：为特定账号设置不同的最大拉取次数
        ACCOUNT_MAX_FETCH.put("account1", 3);
        ACCOUNT_MAX_FETCH.put("account2", 7);
        ACCOUNT_MAX_FETCH.put("account3", 5);
    }
    
    // 默认最大拉取次数
    private static final int DEFAULT_MAX_FETCH_COUNT = 4;
    
    // 请求间隔时间（秒）
    private static final int REQUEST_INTERVAL_SECONDS = 5;
    
    @Override
    public CompletableFuture<Object> fetchData(String accountId, Object params) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟网络请求延迟 - 比第一个接口稍慢
                int delay = ThreadLocalRandom.current().nextInt(1000, 3000);
                Thread.sleep(delay);
                
                // 处理特定的参数，有不同的逻辑
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("accountId", accountId);
                resultData.put("apiType", "API_TWO");
                resultData.put("delayMs", delay);
                
                if (params instanceof RequestParams) {
                    RequestParams requestParams = (RequestParams) params;
                    resultData.put("dataType", requestParams.getDataType());
                    resultData.put("timeRange", requestParams.getStartTime() + " to " + requestParams.getEndTime());
                    // 可以处理extraParams中的特殊逻辑
                    resultData.put("hasExtraParams", requestParams.getExtraParams() != null && !requestParams.getExtraParams().isEmpty());
                }
                
                return resultData;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Fetch data interrupted from API_TWO", e);
            }
        });
    }
    
    @Override
    public boolean shouldContinueFetching(String accountId, int currentCount) {
        // 高级策略：根据账号ID动态确定最大拉取次数
        int maxFetchCount = ACCOUNT_MAX_FETCH.getOrDefault(accountId, DEFAULT_MAX_FETCH_COUNT);
        return currentCount < maxFetchCount;
    }
    
    @Override
    public String getInterfaceType() {
        return "API_TWO";
    }
    
    @Override
    public int getRequestIntervalSeconds() {
        return REQUEST_INTERVAL_SECONDS;
    }
}